/*
 * PsInputWriter.cpp
 *
 *  Created on: 2018年8月9日
 *      Author: zhengboyuan
 */

#include "PsInputWriter.h"
#include "MFormatUtil.h"

namespace av
{

PsInputWriter::PsInputWriter(MediaFileFormat fileFormat)
{
	m_writer.reset(MediaWriterFactory::create(fileFormat));
}

PsInputWriter::~PsInputWriter()
{
	close();
}

bool PsInputWriter::open(const char* filename, const MFormat& fmt)
{
	if (!filename)
	{
		return false;
	}

	if (!m_writer)
	{
		return false;
	}

	m_filename = filename;

	return true;
}

void PsInputWriter::close()
{
	if (!m_writer)
	{
		return;
	}

	m_writer->close();
}

bool PsInputWriter::isOpen()
{
	if (!m_writer)
	{
		return false;
	}

	return m_writer->isOpen();
}

bool PsInputWriter::getFormat(MFormat& fmt)
{
	if (!m_writer)
	{
		return false;
	}

	return m_writer->getFormat(fmt);
}

bool PsInputWriter::writeVideo(uint8_t* data, int size, int64_t pts, int flags)
{
	if (!m_writer)
	{
		return false;
	}

	return writeData(data, size, pts, flags);
}

bool PsInputWriter::writeAudio(uint8_t* data, int size, int64_t pts, int flags)
{
	if (!m_writer)
	{
		return false;
	}

	return writeData(data, size, pts, flags);
}

int PsInputWriter::getDuration()
{
	if (!m_writer)
	{
		return 0;
	}

	return m_writer->getDuration();
}

int64_t PsInputWriter::getByteLength()
{
	if (!m_writer)
	{
		return 0;
	}

	return m_writer->getByteLength();
}

bool PsInputWriter::setFile(const char* filepath)
{
	if (!m_writer)
	{
		return false;
	}

	return m_writer->setFile(filepath);
}

bool PsInputWriter::setOutputAudioCodec(int codecId)
{
	if (!m_writer)
	{
		return false;
	}

	return m_writer->setOutputAudioCodec(codecId);
}

void PsInputWriter::setListener(MediaWriterListener* listener)
{
	if (!m_writer)
	{
		return;
	}

	return m_writer->setListener(listener);
}

bool PsInputWriter::setMeta(const char* key, const char* value, int size)
{
	if (!m_writer)
	{
		return false;
	}

	return m_writer->setMeta(key, value, size);
}

bool PsInputWriter::writeData(uint8_t* data, int size, int64_t pts, int flags)
{
	PsParser::Packet psPacket;
	if (!m_psParser.parse(data, size, psPacket))
	{
		return false;
	}

	if (!m_format.isValid())
	{
		MediaFormat fmt = m_psParser.getFormat();
		if (fmt.isValid())
		{
			m_format = fmt;

			onFormatReady();
		}
		else
		{
			return false;
		}
	}

	if (psPacket.type == av::MEDIA_TYPE_AUDIO)
	{
		return m_writer->writeAudio(psPacket.data, psPacket.length, psPacket.ts, psPacket.flags);
	}
	else
	{
		return m_writer->writeVideo(psPacket.data, psPacket.length, psPacket.ts, psPacket.flags);
	}
}

void PsInputWriter::onFormatReady()
{
	MFormat fmt = MFormat();
	MFormatUtil::copyFrom(&fmt, m_format);

	fmt.audioRate = 90000;

	m_writer->open(m_filename.c_str(), fmt);
}


} /* namespace av */
